﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace HuoTu.Common
{
    /// <summary>
    /// 加密类
    /// 修改者：罗国华
    /// 修改日期：2012.8.2
    /// </summary>
    public class SysCrypto
    {
        private SysCrypto() { }

        #region DES加密
        /// <summary>
        /// 8位密钥
        /// </summary>
        private static string defaultKey = "6h~(I._%";

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="encryptString">要加密的字符串</param>
        /// <returns></returns>
        public static string DESEncrypt(string encryptString)
        {
            return DESEncrypt(encryptString, defaultKey);
        }
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="encryptString">要加密的字符串</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string DESEncrypt(string encryptString, string key)
        {
            return DESEncrypt(encryptString, key, key.Substring(0, 8));
        }

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="encryptString">要加密的字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="iv">位移量</param>
        /// <returns></returns>
        public static string DESEncrypt(string encryptString, string key, string iv)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] keyIV = Encoding.UTF8.GetBytes(iv);
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            string val = Convert.ToBase64String(mStream.ToArray());
            cStream.Close();
            mStream.Close();
            return val;
        }

        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="decryptString">解密的字符串</param>
        /// <returns></returns>
        public static string DESDecrypt(string decryptString)
        {
            return DESDecrypt(decryptString, defaultKey);
        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="decryptString">解密的字符串</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string DESDecrypt(string decryptString, string key)
        {
            return DESDecrypt(decryptString, key, key.Substring(0, 8));
        }


        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="decryptString">解密的字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="iv">位移量</param>
        /// <returns></returns>
        public static string DESDecrypt(string decryptString, string key, string iv)
        {
            string val = string.Empty;
            try
            {
                byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                byte[] keyIV = Encoding.UTF8.GetBytes(iv);
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                val = Encoding.UTF8.GetString(mStream.ToArray());
                cStream.Close();
                mStream.Close();
            }
            catch { }
            return val;
        }

        #endregion

        #region MD5加密
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="text">要加密的文本</param>
        /// <returns>MD5加密后的文本</returns>
        public static string MD5(string text)
        {
            string val = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "MD5");
            val = val.Substring(8, val.Length - 8);
            val = val.Substring(0, val.Length - 8);
            return val.ToLower();
        }

        public static string Md5_32(string input)
        {
            MD5 md5Hasher = System.Security.Cryptography.MD5.Create();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
        #endregion

        #region 文件加密
        /// <summary>
        /// 文件加密
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outFilePath"></param>
        /// <param name="key"></param>
        public static void FileDESEncrypt(string inputFilePath, string outFilePath, string key)
        {
            byte[] keyBytes = null;
            try
            {
                keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                byte[] keyIV = keyBytes;
                FileStream stream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read);
                FileStream stream2 = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
                stream2.SetLength(0L);
                byte[] buffer = new byte[100];
                long num = 0L;
                long length = stream.Length;
                DES des = new DESCryptoServiceProvider();
                CryptoStream stream3 = new CryptoStream(stream2, des.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                while (num < length)
                {
                    int count = stream.Read(buffer, 0, 100);
                    stream3.Write(buffer, 0, count);
                    num += count;
                }
                stream3.Close();
                stream2.Close();
                stream.Close();
            }
            catch (Exception ex) { }
        }
        /// <summary>
        /// 文件解密
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outFilePath"></param>
        /// <param name="key"></param>
        public void FileDESDecrypt(string inputFilePath, string outFilePath, string key)
        {
            byte[] keyBytes = null;
            try
            {
                keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                byte[] keyIV = keyBytes;
                FileStream stream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read);
                FileStream stream2 = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
                stream2.SetLength(0L);
                byte[] buffer = new byte[100];
                long num = 0L;
                long length = stream.Length;
                DES des = new DESCryptoServiceProvider();
                CryptoStream stream3 = new CryptoStream(stream2, des.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                while (num < length)
                {
                    int count = stream.Read(buffer, 0, 100);
                    stream3.Write(buffer, 0, count);
                    num += count;
                }
                stream3.Close();
                stream2.Close();
                stream.Close();
            }
            catch (Exception ex) { }
        }
        #endregion

        #region RSA解密
        /// <summary>
        /// RSA加密算法产生私钥和公钥
        /// </summary>
        /// <param name="xmlKeys">XML格式私钥</param>
        /// <param name="xmlPublicKey">XML格式公钥</param>
        public static void RSAKey(out string xmlKeys, out string xmlPublicKey)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                xmlKeys = rsa.ToXmlString(true);//私钥
                xmlPublicKey = rsa.ToXmlString(false); //公钥
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// RSA加密
        /// </summary>
        /// <param name="publickey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RSAEncrypt(string publickey, string content)
        {
            //publickey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publickey);
            byte[] cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            return Convert.ToBase64String(cipherbytes);
        }
        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="privatekey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RSADecrypt(string privatekey, string content)
        {
            //privatekey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent><P>/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==</P><Q>6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==</Q><DP>ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==</DP><DQ>MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==</DQ><InverseQ>EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==</InverseQ><D>vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=</D></RSAKeyValue>";
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(privatekey);
            byte[] cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
            return Encoding.UTF8.GetString(cipherbytes);
        }

        #endregion
    }
}